package com.yaoli.ajob;

/**
 * Created by will on 2017/6/12.
 */
public class _617_MergeTwoBinaryTrees {
    public static void main(String[] args) {
        TreeNode  a = new TreeNode(1);
        TreeNode  b = new TreeNode(3);
        TreeNode  c = new TreeNode(2);
        TreeNode  d = new TreeNode(5);

        a.setLeft(b);
        a.setRight(c);
        c.setLeft(d);

        TreeNode  e = new TreeNode(2);
        TreeNode  f = new TreeNode(1);
        TreeNode  g = new TreeNode(3);
        TreeNode  h = new TreeNode(4);
        TreeNode  i = new TreeNode(7);

        e.setLeft(f);
        e.setRight(g);

        f.setRight(h);
        g.setRight(i);

        _617_MergeTwoBinaryTrees mergeTwoBinaryTrees = new _617_MergeTwoBinaryTrees();
        mergeTwoBinaryTrees.mergeTrees(a,e);


    }

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null && t2 == null){
            return null;
        }

        TreeNode root = new TreeNode(0);

        TreeNode tmp = calc(root,t1,t2);

        return tmp;
    }

    public TreeNode calc(TreeNode root , TreeNode t1 , TreeNode t2){
        if(t1 == null && t2 == null){
            return null;
        }else{
            root = getNode(t1,t2);

            if(t1 != null && t2 != null){
                root.left = calc(root.left,t1.left,t2.left);
                root.right = calc(root.right,t1.right,t2.right);
            }else if(t1 != null && t2 == null){
                root.left = calc(root.left,t1.left,null);
                root.right = calc(root.right,t1.right,null);
            }else if(t1 == null && t2 != null){
                root.left = calc(root.left,null,t2.left);
                root.right = calc(root.right,null,t2.right);
            }

            return root;
        }
    }

    public TreeNode getNode(TreeNode t1,TreeNode t2){
        if(t1 == null && t2 == null){
            return null;
        }else{
            int value = getValue(t1)+getValue(t2);
            TreeNode node = new TreeNode(value);
            return node;
        }
    }

    public int getValue(TreeNode node){
        return node == null ? 0 : node.val;
    }
}
